<template>
  <div class="order-manage-container">
    <h1 class="page-title">订单管理</h1>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 订单列表 -->
    <div v-else class="order-list">
      <div v-for="order in orders" :key="order.id" class="order-item">
        <div class="order-header">
          <span class="order-number">订单号：{{ order.orderNumber }}</span>
          <el-tag :type="statusTag(order.status)">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>

        <div class="order-content">
          <!-- 房屋信息 -->
          <div class="house-info">
            <div class="house-title">{{ order.house.title }}</div>
            <div class="house-address">
              <el-icon><Location /></el-icon>
              {{ order.house.address }}
            </div>
          </div>

          <!-- 交易双方 -->
          <div class="participants">
            <div class="tenant">
              <span class="label">租客：</span>
              <span class="name">{{ order.customer.name }}</span>
              <span class="phone">{{
                order.customer.phone || "未提供电话"
              }}</span>
            </div>
            <div class="landlord">
              <span class="label">房东：</span>
              <span class="name">{{ order.owner.name }}</span>
              <span class="phone">{{ order.owner.phone || "未提供电话" }}</span>
            </div>
          </div>

          <!-- 时间信息 -->
          <div class="time-range">
            <span class="time-label">租赁周期：</span>
            {{ order.startDate }} 至 {{ order.endDate }}
            <el-tag size="small">共 {{ order.dayNum }} 天</el-tag>
          </div>
          <div v-if="order.status === 3 && isLandlord" class="time-range">
            <span class="time-label">退租原因：</span
            ><span class="time-label">{{ order.reason }}</span>
          </div>

          <!-- 金额信息 -->
          <div class="amount-info">
            <span class="total-amount"
              >总金额：¥{{ formatAmount(order.totalAmount) }}</span
            >
          </div>

          <!-- 拒绝理由（仅限租客可见） -->
          <div v-if="order.status === 4 && !isLandlord" class="refusal-reason">
            <span class="reason-label">拒绝理由：</span>
            <p>{{ order.refusalReason }}</p>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
            v-if="order.status === -2 && isTenant"
            type="primary"
            @click="handleSign(order)"
          >
            立即签署
          </el-button>
          <el-button @click="viewContract(order)"> 查看合同 </el-button>
          <el-button
            v-if="order.status === 3 && isLandlord"
            type="danger"
            @click="openRefusalDialog(order)"
          >
            拒绝退租
          </el-button>
          <el-button
            v-if="order.status === 3 && isLandlord"
            type="success"
            @click="agreeOrder(order)"
          >
            同意退租
          </el-button>
        </div>
      </div>
    </div>

    <!-- 拒绝退租对话框 -->
    <el-dialog
      v-model="refusalReasonVisible"
      title="拒绝退租"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="refusalForm" label-width="80px">
        <el-form-item label="拒绝原因">
          <span>拒绝后改订单会有管理员接入来调节双方，来由三方决定结果</span>
          <el-input
            v-model="refusalForm.refusalReason"
            type="textarea"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refusalReasonVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRefusal()">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { Location } from "@element-plus/icons-vue";
import api from "@/api";
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";

const userStore = useUserStore();
const orders = ref([]);
const loading = ref(true);
const route = useRoute();
const router = useRouter();

// 审核原因相关变量
const reviewReasonVisible = ref(false);
const reviewReason = ref("");

// 拒绝原因相关变量
const refusalReasonVisible = ref(false);
const refusalForm = ref({
  orderId: null,
  refusalReason: "",
});

// 状态映射
const statusMap = {
  "-2": { text: "待签署", type: "warning" },
  "-1": { text: "待支付", type: "danger" },
  0: { text: "生效中", type: "success" },
  1: { text: "已退租", type: "info" },
  2: { text: "待审核", type: "info" },
  3: { text: "申请退租", type: "warning" }, // 假设3代表申请退租状态
};

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount).toLocaleString("zh-CN");
};

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status]?.text || "未知状态";
};

// 获取状态标签颜色
const statusTag = (status) => {
  return statusMap[status]?.type || "info";
};

// 判断是否为房东
const isLandlord = computed(() => {
  return userStore.userInfo.roles.some((r) => r.name === "ROLE_Landlord");
});

// 判断是否为租客
const isTenant = computed(() => {
  return userStore.userInfo.roles.some((r) => r.name === "ROLE_Tenant");
});

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    const params = {};

    // 根据角色添加查询参数
    if (userStore.userInfo.roles.some((r) => r.name === "ROLE_Tenant")) {
      params.customerId = userStore.userInfo.id;
    } else if (
      userStore.userInfo.roles.some((r) => r.name === "ROLE_Landlord")
    ) {
      params.ownerId = userStore.userInfo.id;
    }

    const { data } = await api.order.getOrderList(params);
    orders.value = data.data.map((order) => ({
      ...order,
      refusalReason: order.refusalReason || "", // 初始化拒绝理由为空字符串
    }));
  } catch (error) {
    ElMessage.error("获取订单失败: " + error.message);
  } finally {
    loading.value = false;
  }
};

// 处理支付
const handlePayment = (order) => {
  console.log("支付订单:", order);
};

// 查看合同（隐藏签署功能）
const viewContract = (order) => {
  router.push({
    path: "/contract",
    query: {
      orderId: order.id,
      mode: "view", // 添加模式参数
    },
  });
};

// 立即签署（显示签署功能）
const handleSign = (order) => {
  router.push({
    path: "/contract",
    query: {
      orderId: order.id,
      mode: "sign",
    },
  });
};

// 显示审核原因
const showReviewReason = async (order) => {
  try {
    const { data } = await api.order.getOrderDetail(order.id);
    reviewReason.value = data.reason;
    reviewReasonVisible.value = true;
  } catch (error) {
    ElMessage.error("获取审核原因失败: " + error.message);
  }
};

// 打开拒绝退租对话框
const openRefusalDialog = (order) => {
  refusalForm.value.orderId = order.id;
  refusalForm.value.refusalReason = "";
  refusalReasonVisible.value = true;
};

// 提交拒绝原因
const submitRefusal = async () => {
  const { orderId, refusalReason } = refusalForm.value;
  try {
    if (!refusalReason) {
      ElMessage.warning("请输入拒绝原因");
      return;
    }
    await api.order.refuseOrder(orderId, refusalReason);
    ElMessage.success("已拒绝退租请求");
    refusalReasonVisible.value = false;
    fetchOrders(); // 刷新订单列表
  } catch (error) {
    ElMessage.error("拒绝退租失败: " + error.message);
  }
};

// 同意退租
const agreeOrder = async (order) => {
  try {
    await api.order.agreeOrder(order.id);
    ElMessage.success("已同意退租请求");
    fetchOrders(); // 刷新订单列表
  } catch (error) {
    ElMessage.error("同意退租失败: " + error.message);
  }
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped lang="css">
/* 保持原有样式不变 */
.order-manage-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.loading-container {
  padding: 40px 0;
}

.page-title {
  color: #303133;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.order-item {
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;

  + .order-item {
    margin-top: 16px;
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .order-number {
    font-size: 15px;
    color: #606266;
  }
}

.house-info {
  margin-bottom: 16px;

  .house-title {
    font-size: 16px;
    color: #303133;
    margin-bottom: 8px;
  }

  .house-address {
    display: flex;
    align-items: center;
    color: #606266;
    font-size: 14px;

    .el-icon {
      margin-right: 6px;
      color: #909399;
    }
  }
}

.participants {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 16px;

  > div {
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;

    .label {
      color: #909399;
      margin-right: 8px;
    }

    .name {
      color: #303133;
      margin-right: 12px;
    }

    .phone {
      color: #606266;
    }
  }
}

.time-range {
  margin-bottom: 12px;
  color: #606266;

  .time-label {
    color: #909399;
  }
}

.amount-info {
  text-align: right;

  .total-amount {
    font-size: 18px;
    color: #e74c3c;
    font-weight: 500;
  }
}

.action-buttons {
  margin-top: 16px;
  text-align: right;

  .el-button + .el-button {
    margin-left: 12px;
  }
}

.refusal-reason {
  margin-top: 16px;
  background: #fef0f0;
  padding: 12px;
  border-radius: 4px;
  color: #d9534f;

  .reason-label {
    font-weight: bold;
  }
}
</style>
